package com.simon.annual.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.simon.annual.entity.CompanyPublic;
import com.simon.annual.entity.ReportCompany;
import com.simon.annual.repositoy.ICompanyPublicRepositoy;
import com.simon.annual.repositoy.IReportCompanyRepositoy;

/**
 *第二节：公司概况 
 * */
@Service
public class CompanyPublicInfoImpl{

	@Resource
	private ICompanyPublicRepositoy companyPublicRepositoy;
	@Resource
	private IReportCompanyRepositoy reportCompanyRepositoy;
	@Resource
	private Environment env;
	
	
	public void analysis(Element na, int companyPtrId) {
		//基本信息
		Element ed = findNextTag("table", na);
		Elements tds = ed.select("table tr  > *");
		ReportCompany reportCompany = new ReportCompany();
		reportCompany.setNameZh(tds.get(1).text());
		reportCompany.setNameEn(tds.get(3).text());
		reportCompany.setStockAbbr(tds.get(5).text());
		reportCompany.setStockCode(tds.get(7).text());
		reportCompany.setLegalRep(tds.get(9).text());
		reportCompany.setRegAddress(tds.get(11).text());
		reportCompany.setOfficeAddress(tds.get(13).text());
		reportCompany.setBroker(tds.get(15).text());
		reportCompany.setBrokerAddress(tds.get(17).text());
		reportCompany.setCpaFirm(tds.get(19).text());
		reportCompany.setCpa(tds.get(21).text());
		reportCompany.setCpaAddress(tds.get(23).text());
		//联系方式
		Element el = findNextTag("table", ed);
		Elements td = el.select("table tr  > *");
		reportCompany.setCompanySecretary(td.get(1).text());
		reportCompany.setPhoneNo(td.get(3).text());
		reportCompany.setFaxNo(td.get(5).text());
		reportCompany.setEmailAddress(td.get(7).text());
		reportCompany.setWebsiteAddress(td.get(9).text());
		reportCompany.setContactAddress(td.get(11).text());
		reportCompany.setDisclosureWebsite(td.get(13).text());
		reportCompany.setLocationOfAnnualReport(td.get(15).text());
		//企业信息
		Element com = findNextTag("table", el);
		Elements comTds = com.select("table tr > *");
		reportCompany.setListMarket(comTds.get(1).text());
		reportCompany.setListDate(comTds.get(3).text());
		reportCompany.setIndustry(comTds.get(5).text());
		reportCompany.setMainProduct(comTds.size()>7?comTds.get(7).text():"");
		reportCompany.setTradeType(comTds.size()>9?comTds.get(9).text():"");
		reportCompany.setCapitalization(comTds.size()>11?comTds.get(11).text():"");
		reportCompany.setControllingStake(comTds.size()>13?comTds.get(13).text():"");
		reportCompany.setActualController(comTds.size()>15?comTds.get(15).text():"");
		//注册信息
		Element reg = findNextTag("table", com);
		Elements regTd = reg.select("table tr > *");
		reportCompany.setRegCode(regTd.get(4).text());
		reportCompany.setIsRegCodeChanged(regTd.get(5).text());
		reportCompany.setTaxCode(regTd.get(7).text());
		reportCompany.setIsTaxCodeChanged(regTd.get(8).text());
		reportCompany.setOrgCode(regTd.size()>10?regTd.get(10).text():"");
		reportCompany.setIsOrgCodeChanged(regTd.size()>11?regTd.get(11).text():"");
		reportCompany.setProjectScopeId(companyPtrId);
		reportCompanyRepositoy.save(reportCompany);
	}
	
	public int getCompanyPtrId(Document doc) {
		List<CompanyPublic> companyPublicList = companyPublicRepositoy.findByStockCode(getNeeqCode(doc));
		return companyPublicList.get(0).getCompanyPtrId();
	}

	public Document init(String path) {
		try {
			Document doc = Jsoup.parse(new File(path),"UTF-8");
			String html = doc.html();
//			Jsoup.clean(html, Whitelist.relaxed());
			//<sect>
			html = html.replaceAll("<sect(.*)>", "").replaceAll("</sect>", "");
			//<part>
			html = html.replaceAll("<part(.*)>", "").replaceAll("</part>", "");
			//<Document>
			html = html.replaceAll("<document(.*)>", "").replaceAll("</document>", "");
			doc = Jsoup.parse(html);
			return cleanDom(doc);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private Document cleanDom(Document doc) {
		Elements  Ap = doc.select("p");
		for (Element element : Ap) {
			if(!element.hasText()){
				element.remove();
			}
		}
		doc.select("toc").remove();
		return doc;
	}
	
	/**
	 * 获取股票代码
	 * */
	public String getNeeqCode(Document doc){
		Elements neeq = doc.getElementsMatchingOwnText(env.getProperty("pdf.companyPtrId"));
		if(!neeq.hasText()){
			Element neeqE = doc.select("p:contains(NEEQ)").first();
			return neeqE.text().replaceAll("\\D+", "");
		}
		for (Element ele : neeq) {
			if(ele.text().length()<5){
				Element pa = ele.parent();
				if(!pa.tagName().equals("tr")){
					pa = pa.parent();
					ele = ele.parent();
				}
				if(pa.tagName().equals("tr")&&pa.parent().parent().tagName().equals("table")
						&&pa.children().size()==2){
					return ele.nextElementSibling().text();
				}
			}
		}
		return null;
	}

	
	/**
	 *合并跨页表格
	 * */
	public Element getNextTag(Element e, Element newElement) {
		Element tag = e.nextElementSibling();
		if(tag!=null&&tag.tagName().equals("table")){
			//判断合并的结构是否一致 不一致则不属于合并范围
//			if(newElement.select("table tr").last().children().size()!=tag.select("table tr").first().children().size()){
//				return newElement;
//			}
//			tag.
			newElement = newElement.prependChild(tag);
			Element nexttag = newElement;
			tag.remove();
			return getNextTag(nexttag,newElement);
		}else{
//			Elements ss = newElement.select("td table tbody");
//			for (Element element : ss) {
//				String html = element.html();
//				element.parent().remove();
//				newElement.select("tr").last().after(html);
//			}
			Elements tbodys = newElement.select("tbody");
			//合并分页table
			if(tbodys.size()>1){
				for (int i = 0; i < tbodys.size()-1; i++) {
					Element body = tbodys.get(i+1);
					Elements  element = body.select("tr");
					if(!element.isEmpty()){
//						boolean ps = element.first().select("td p").size()==tbodys.get(i).select("tr").last().select("td p").size();
						boolean ps = element.first().children().size()==tbodys.get(i).select("tr").last().children().size();
						if(ps&&!tbodys.get(i).select("tr").last().children().first().hasText()){
							Elements eTd = element.first().children();
							for (int j = 0; j < eTd.size(); j++) {
								tbodys.get(i).select("tr").last().child(j).appendText(eTd.get(j).text());
							}
							element.first().remove();
							if(!tbodys.get(i+1).hasText()){
								tbodys.remove(i+1);
							}
						}
					}
				}
			}
			return newElement;
		}
	}

	/**
	 * 查找当前节点下一个同级节点
	 * */
	public Element findNextTag(String tag,Element e){
		Element next = e.nextElementSibling();
		//获取非同级元素
//		boolean hasTable = next.children().select("table").size()>0;
//		next = hasTable?next.select("table").first():next;
		if(next.tagName().equals("table")){//合并table
			next = getNextTag(next,next);
		}
		boolean s = next.tagName().equals(tag);
//		next = hasTable?next.parent():next;
		return s?next:findNextTag(tag,next);
	}
	/**
	 * 查找当前节点下一个第N个同级节点
	 * */
	public Element findNextTag(String tag,Element e,int n){
		Element ne =e;
		for (int i = 1; i <= n; i++) {
			 ne = findNextTag(tag,ne);
		}
		return ne;
	}

	/**
	 * 查找当前节点下一个同级节点
	 * */
	public Element findNextTagNoMer(String tag,Element e){
		Element next = e.nextElementSibling();
		boolean s = next.tagName().equals(tag);
		return s?next:findNextTag(tag,next);
	}
	
	public Element buildTable(Element e){
		Elements els = e.select("tr");
		for (int i = 1; i < els.size(); i++) {
			if(els.get(i).children().size()!=els.first().children().size()){
				els.get(i-1).children().last().appendText(els.get(i).text());
				els.get(i).remove();
			}
		}
		return e;
	}

	public Element findNextByChar(String chars, Element e ,int index) {
		Element next = e.nextElementSibling();
		index++;
		if(index>5){
			return null;
		}
		boolean s = next.text().indexOf(chars)>-1;
		return s?next:findNextByChar(chars,next,index);
	}
}
